package com.library.lms.controller;


import com.library.lms.entity.User;
import com.library.lms.entity.UserInfo;
import com.library.lms.service.UserInfoService;
import com.library.lms.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/regist")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoService userInfoService;

    @PostMapping("/add")
    public Map<String, Object> adduser(@RequestBody Map<String,String>  param,
                                        HttpServletRequest request,
                                        HttpServletResponse response) {
        HashMap<String, Object> map = new HashMap<>();
        String s = param.get("code").toUpperCase();
        Object code = request.getSession(true).getAttribute("code");

        if (s.equals(code)){
            User userBuild = User.builder().name(param.get("name"))
                    .password(DigestUtils.md5DigestAsHex(param.get("password").getBytes()))
                    .type("1").build();
            int i = userService.addUserInfo(userBuild);
            System.out.println(i);
            if (i > 0) {
                UserInfo userInfobuild = UserInfo.builder().realName(param.get("name"))
                        .tel(param.get("tel"))
                        .userId(userBuild.getId())
                        .address(param.get("address"))
                        .school(param.get("school"))
                        .build();
                userInfoService.addUserInfo(userInfobuild);
                map.put("status", 200);
                map.put("msg", "注册成功");
                return map;
            }
        }
        map.put("msg", "验证码错误");
        log.info("接收到的code是[{}]",s);
        log.info("服务器code是[{}]",code);
        return map;
    }
}
